//
//  ShoppingUIM.m
//  mbstore
//
//  Created by huangyi on 14-3-12.
//  Copyright (c) 2014年 huangyi. All rights reserved.
//

#import "ShoppingUIM.h"
#import "ShoppingRow.h"
#import "ShoppingPromotion.h"

@interface ShoppingUIM ()

@property(nonatomic,strong)NSMutableArray *skus;

@end

@implementation ShoppingUIM

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.modalPresentationStyle=UIModalPresentationFormSheet;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    UIButton *cancel=[UIButton buttonWithType:UIButtonTypeCustom];
    [cancel setTitle:@"取消" forState:UIControlStateNormal];
    [cancel sizeToFit];
    [cancel addTarget:self action:@selector(onCancelClick:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItems=@[cancel.barButtonItem];

    UIButton *clear=[UIButton buttonWithType:UIButtonTypeCustom];
    [clear setTitle:@"清空购物袋" forState:UIControlStateNormal];
    [clear sizeToFit];
    [clear addTarget:self action:@selector(onClearClick:) forControlEvents:UIControlEventTouchUpInside];
//    UIButton *promotion=[UIButton buttonWithType:UIButtonTypeCustom];
//    [promotion setTitle:@"门店促销设置" forState:UIControlStateNormal];
//    [promotion sizeToFit];
//    [promotion addTarget:self action:@selector(onPromotionClick:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItems=@[clear.barButtonItem];

//    self.navigationController.toolbarHidden=NO;
//    UIButton *delete=[UIButton buttonWithImage:[UIImage imageNamed:@"media.bundle/delete.png"]];
//    delete.frame=CGRectMake(0, 0, 40, 40);
//    [delete addTarget:self action:@selector(onDeleteClick:) forControlEvents:UIControlEventTouchUpInside];
//    UIBarButtonItem *space=[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
//    UITableViewCell *cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue2 reuseIdentifier:@"total"];
//    cell.backgroundColor=[UIColor clearColor];
//    cell.frame=CGRectMake(0, 0, 200, 40);
//    cell.textLabel.text=@"商品总价：";
//    cell.detailTextLabel.text=@"¥";
//    cell.detailTextLabel.textColor=[UIColor redColor];
//    cell.detailTextLabel.font=[UIFont systemFontOfSize:20];
//    self.toolbarItems=@[delete.barButtonItem,space,cell.barButtonItem];
//    self.navigationController.toolbar.frame=CGRectMake(0, 0, 300, 100);
//    self.sumCell=cell;

    self.title=@"购物袋";
    [self SetCustom];
}
-(void)SetCustom{
    UIImageView *img=[[UIImageView alloc]initWithFrame:CGRectMake(9, 5, 28, 32)];
    img.image=[UIImage imageNamed:@"media.bundle/delete.png"];
    
    self.labStartPrice.strikeThroughEnabled=YES;
    [self.btnDelete addSubview:img];
    [self.btnDelete setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)onCancelClick:(id)sender{
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}

-(void)onClearClick:(id)sender{
    MainApp *app=[MainApp mainApp];
    [app.shoppingList removeAllObjects];
    [self createShoppingList];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:ShoppingListNotification object:self];
}

-(void)onPromotionClick:(id)sender{
    ShoppingPromotion *promo=[[ShoppingPromotion alloc] init];
    [self.navigationController pushViewController:promo animated:YES];
}


- (IBAction)PressDelete:(id)sender {
    NSMutableArray *array=[NSMutableArray array];
    for (ShoppingItem *item in self.skus) {
        if (item.selected) {
            [array addObject:item.skuId];
        }
    }
    int idx=0;
    MainApp *app=[MainApp mainApp];
    while (idx<app.shoppingList.count) {
        NSString *skuId=app.shoppingList[idx];
        BOOL found=NO;
        for (ShoppingItem *item in self.skus) {
            if ([item.skuId isEqualToString:skuId]) {
                if (item.selected) {
                    found=YES;
                    break;
                }
            }
        }
        if (found) {
            [app.shoppingList removeObjectAtIndex:idx];
        }else{
            idx++;
        }
    }
    [self createShoppingList];
    [[NSNotificationCenter defaultCenter] postNotificationName:ShoppingListNotification object:self];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.skus.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 120;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *identifier=@"shopping";
    UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier];
        cell.clipsToBounds=YES;
        cell.selectionStyle=UITableViewCellSelectionStyleGray;
        ShoppingRow *row=(id)[NibLoader loadNib:@"ShoppingRow"];
        [cell.contentView addSubview:row];
        row.frame=cell.contentView.bounds;
        row.tag=1001;
    }

    ShoppingRow *row=(id)[cell.contentView viewWithTag:1001];
    [row prepareForReuse];

    ShoppingItem *obj=self.skus[indexPath.row];
    [row setItem:obj];
    if (obj.selected) {
        [row setCheckmark:YES];
    }else{
        [row setCheckmark:NO];
    }
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    ShoppingItem *item=self.skus[indexPath.row];
    item.selected=!item.selected;
    [tableView reloadData];
}

-(void)createShoppingList{
    NSMutableDictionary *counter=[NSMutableDictionary dictionary];
    MainApp *app=[MainApp mainApp];
    for (NSString *skuId in app.shoppingList) {
        ShoppingItem *item=counter[skuId];
        if (!item) {
            item=[[ShoppingItem alloc] init];
            counter[skuId]=item;
        }
        item.skuId=skuId;   
        item.count++;
        item.selected=NO;
    }
    self.skus=[NSMutableArray arrayWithArray:[counter allValues]];
    [self.tableView reloadData];
    [self requestDiscount];
    [self sumPrice];
}

-(void)sumPrice{
    double sum=0;
    for (ShoppingItem *item in self.skus) {
        if (item.finalPrice) {
            double unit=[item.finalPrice doubleValue];
            sum+=unit*item.count;
        }else{
            double unit=[item.price doubleValue];
            sum+=unit*item.count;
        }
    }
//    self.sumCell.detailTextLabel.text=[NSString stringWithFormat:@"¥%@",@(sum)];
    self.labSaveMoney.text=[NSString stringWithFormat:@"¥%@",@(sum)];
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self createShoppingList];
}

#warning TODO: 折扣
//先查询商品信息缓存，构造折扣BillSaleDetails，将返回的折扣结果根据ProdID生成字典，然后购物车列表根据ProdID字典获取DivSalesValue，DivDiscountRate，然后main线程更新视图
-(void)requestDiscount{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSMutableArray *infos=[NSMutableArray array];
        MainApp *app=[MainApp mainApp];
        for (NSString *skuId in app.shoppingList) {
            NSDictionary *product=[app requestProduct:skuId];
            if (product) {
                [infos addObject:product];
            }
        }
        NSMutableDictionary *pdts=[NSMutableDictionary dictionary];
        if (infos.count) {
            HTTPClient *client=[AppUI getDiscount:infos];
            if (!client.error) {
                NSDictionary *result=[client.responseData JSONObject];
                NSArray *discounts=[result valueForKey:@"DetailEntitys"];
                for (NSDictionary *discount in discounts) {
                    NSString *prodId=discount[@"ProdID"];
                    [pdts setValue:discount forKey:prodId];
                }
            }
        }
        for (ShoppingItem *item in self.skus) {
            item.finalPrice=item.price;
            item.discount=@"查询失败";
            NSDictionary *product=[app requestProduct:item.skuId];
            if (product) {
                NSString *prodID=product[@"ProdID"];
                NSDictionary *discount=[pdts valueForKey:prodID];
                if (discount) {
                    item.finalPrice=[NSString stringWithFormat:@"%@",discount[@"DivSalesValue"]];
                    item.discount=[NSString stringWithFormat:@"%@%%",discount[@"DivDiscountRate"]];
                }
            }
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
            [self sumPrice];
        });
    });
}


@end
